package com.howells.time.module.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.howells.time.base.utils.SharedPrefsUtil;

/**
 * Created by Administrator on 2016.5.26.
 */
public class TimeService extends Service {

    private LocationService mLocation;

    @Override
    public void onCreate() {
        super.onCreate();
        mLocation = new LocationService(getApplication());
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        mLocation.registerListener(mListener);
        //注册监听
        mLocation.setLocationOption(mLocation.getDefaultLocationClientOption());

        mLocation.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        mLocation.unregisterListener(mListener); //注销掉监听
        mLocation.stop(); //停止定位服务
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {

            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                StringBuffer sb = new StringBuffer(256);
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */
                sb.append("\nlatitude : ");
                sb.append(location.getLatitude());
                sb.append("\nlontitude : ");
                sb.append(location.getLongitude());
                Log.d("TimeService", sb.toString());

                SharedPrefsUtil.putValue(getApplicationContext(),"location","latitude", (float) location.getLatitude());
                SharedPrefsUtil.putValue(getApplicationContext(),"location","longitude", (float) location.getLongitude());

            }
        }

    };
}
